<template>
  <div class="order-container">
    <h2 class="page-title">我的订单</h2>
    
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部订单" name="all"></el-tab-pane>
      <el-tab-pane label="待支付" name="0"></el-tab-pane>
      <el-tab-pane label="已支付" name="1"></el-tab-pane>
      <el-tab-pane label="配送中" name="2"></el-tab-pane>
      <el-tab-pane label="已完成" name="3"></el-tab-pane>
      <el-tab-pane label="已取消" name="4"></el-tab-pane>
    </el-tabs>
    
    <div class="order-list" v-loading="loading">
      <div v-if="orders.length === 0" class="empty-data">
        暂无订单数据
      </div>
      
      <el-card v-for="order in orders" :key="order.id" class="order-card">
        <div class="order-header">
          <div class="order-restaurant">
            <span class="restaurant-name">{{ order.restaurantName }}</span>
            <el-tag :type="getStatusType(order.status)" size="small">{{ getStatusText(order.status) }}</el-tag>
          </div>
          <div class="order-no">订单号：{{ order.orderNo }}</div>
        </div>
        
        <div class="order-items">
          <div v-for="item in order.orderItems" :key="item.id" class="order-item">
            <img :src="item.dishImage" :alt="item.dishName" class="dish-image">
            <div class="item-info">
              <div class="item-name">{{ item.dishName }}</div>
              <div class="item-count">x {{ item.quantity }}</div>
            </div>
            <div class="item-price">¥{{ item.dishPrice * item.quantity }}</div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-info">
            <div class="info-item">下单时间：{{ formatDate(order.createTime) }}</div>
            <div class="info-item">配送地址：{{ order.receiverAddress }}</div>
            <div class="info-item">联系电话：{{ order.receiverPhone }}</div>
          </div>
          <div class="order-total">
            共 {{ getTotalCount(order.orderItems) }} 件商品，实付：
            <span class="total-price">¥{{ order.payAmount }}</span>
          </div>
          <div class="order-actions">
            <el-button v-if="order.status === 0" size="small" type="primary" @click="payOrder(order.id)">立即支付</el-button>
            <el-button v-if="order.status === 0" size="small" type="danger" @click="cancelOrder(order.id)">取消订单</el-button>
            <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
          </div>
        </div>
      </el-card>
      
      <el-pagination
        v-if="orders.length > 0"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="60%">
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ currentOrder.orderNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatDate(currentOrder.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(currentOrder.status)" size="small">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>配送信息</h4>
          <div class="detail-item">
            <span class="label">收货人：</span>
            <span>{{ currentOrder.receiverName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ currentOrder.receiverPhone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">配送地址：</span>
            <span>{{ currentOrder.receiverAddress }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>餐厅信息</h4>
          <div class="detail-item">
            <span class="label">餐厅名称：</span>
            <span>{{ currentOrder.restaurantName }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>商品信息</h4>
          <el-table :data="currentOrder.orderItems" border>
            <el-table-column prop="dishName" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="dishPrice" label="单价" width="100">
              <template slot-scope="scope">¥{{ scope.row.dishPrice }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
            <el-table-column label="小计">
              <template slot-scope="scope">¥{{ scope.row.dishPrice * scope.row.quantity }}</template>
            </el-table-column>
          </el-table>
          
          <div class="order-summary">
            <div class="summary-item">
              <span>商品总价：</span>
              <span>¥{{ currentOrder.totalAmount }}</span>
            </div>
            <div class="summary-item">
              <span>配送费：</span>
              <span>¥{{ currentOrder.deliveryFee }}</span>
            </div>
            <div class="summary-item total">
              <span>实付金额：</span>
              <span>¥{{ currentOrder.payAmount }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Order',
  data() {
    return {
      loading: false,
      activeTab: 'all',
      orders: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      currentOrder: null
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    fetchOrders() {
      this.loading = true
      const params = {
        page: this.currentPage,
        size: this.pageSize
      }
      
      if (this.activeTab !== 'all') {
        params.status = this.activeTab
      }
      
      this.$http.get('/order/list', { params })
        .then(response => {
          const { data } = response.data
          this.orders = data.records
          this.total = data.total
        })
        .catch(error => {
          this.$message.error('获取订单列表失败')
          console.error('获取订单列表失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleTabClick() {
      this.currentPage = 1
      this.fetchOrders()
    },
    handleCurrentChange() {
      this.fetchOrders()
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'success',
        4: 'info'
      }
      return typeMap[status] || 'info'
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    getTotalCount(items) {
      return items.reduce((sum, item) => sum + item.quantity, 0)
    },
    payOrder(orderId) {
      this.$confirm('确认支付该订单吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.put(`/order/${orderId}/pay`)
          .then(() => {
            this.$message.success('支付成功')
            this.fetchOrders()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '支付失败')
          })
      }).catch(() => {})
    },
    cancelOrder(orderId) {
      this.$confirm('确认取消该订单吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.put(`/order/${orderId}/cancel`)
          .then(() => {
            this.$message.success('订单已取消')
            this.fetchOrders()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '取消订单失败')
          })
      }).catch(() => {})
    },
    viewOrderDetail(orderId) {
      this.$http.get(`/order/${orderId}`)
        .then(response => {
          this.currentOrder = response.data.data
          this.dialogVisible = true
        })
        .catch(error => {
          this.$message.error('获取订单详情失败')
          console.error('获取订单详情失败', error)
        })
    }
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 20px;
}

.empty-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-restaurant {
  display: flex;
  align-items: center;
}

.restaurant-name {
  font-weight: bold;
  font-size: 16px;
  margin-right: 10px;
}

.order-no {
  color: #909399;
  font-size: 14px;
}

.order-items {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.dish-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.item-count {
  color: #909399;
  font-size: 12px;
}

.item-price {
  font-weight: bold;
  color: #f56c6c;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  flex-wrap: wrap;
}

.order-info {
  flex: 1;
}

.info-item {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.order-total {
  font-size: 14px;
  color: #606266;
  margin: 0 20px;
}

.total-price {
  font-weight: bold;
  color: #f56c6c;
  font-size: 18px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

/* 订单详情样式 */
.order-detail {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item .label {
  width: 100px;
  color: #909399;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.summary-item {
  margin-bottom: 10px;
}

.summary-item.total {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
